using UnityEngine;
using UnityEngine.UI;
using Mirror;
using TMPro;
public class PlayerControl : NetworkBehaviour //MonoBehaviour --> NetworkBehaviour
{
    private Rigidbody2D rb; // 刚体组件
    private Collider2D coll; // 碰撞体组件
    private Animator anim; // 动画组件
    public float jumpForce; // 移动速度和跳跃力度
    public Transform groundCheck; // 地面检测点
    public LayerMask ground; // 地面图层
    public bool isGround, isJump; // 是否在地面上，是否跳跃
    public int canJumpCount = 2;// 可跳跃次数
    bool jumpPressed; // 是否按下跳跃键
    int jumpCount; // 跳跃次数
    //检测范围
    public float checkRadius;

    public GameObject bomb;
    void Start()
    {
        rb = GetComponent<Rigidbody2D>(); // 获取刚体组件
        coll = GetComponent<Collider2D>(); // 获取碰撞体组件
        anim = gameObject.GetComponentInChildren<Animator>(); // 获取动画组件
    }
    void Update()
    {
        if (!isLocalPlayer) return;
        if (Input.GetButtonDown("Jump") && jumpCount > 0)
        {
            jumpPressed = true; // 如果按下跳跃键并且还有跳跃次数，设置 jumpPressed 为 true
        }
        SwitchAnim();//动画切换

        //生成炸弹
        if (Input.GetMouseButtonDown(1))
        {
            Cmdshoot();
        }
    }

    [Command]
    private void Cmdshoot()
    {
        //同步方法一
        GameObject b = Instantiate(bomb, transform.position, Quaternion.identity);
        b.GetComponent<Rigidbody2D>().AddForce(Vector2.up * 500f);
        Destroy(b, 1.0f);//两秒后删除
        NetworkServer.Spawn(b);//服务器孵化，同步客户端
        //同步方法二
        // RpcWeaponFire();
    }

    [ClientRpc]
    private void RpcWeaponFire()
    {
        GameObject b = Instantiate(bomb, transform.position, Quaternion.identity);
        b.GetComponent<Rigidbody2D>().AddForce(Vector2.up * 500f);
    }


    //画出的射线可以看见
    private void OnDrawGizmosSelected()
    {
        if (groundCheck != null)
        {
            Gizmos.color = Color.red;
            Gizmos.DrawWireSphere(groundCheck.position, checkRadius);
        }

    }

    //需要把name和颜色同步给其他玩家，添加同步变量的标记[SyncVar(hook=nameof(FunctionExecOnClient))]
    [SyncVar(hook = nameof(OnPlayerNameChanged))]
    public string playerName;
    [SyncVar(hook = nameof(OnPlayerColorChanged))]
    private Color playerColor;

    //速度：每秒移动5个单位长度
    public float moveSpeed = 6;
    public TMP_Text nameText;
    private Chat chat;

    //申明OnPlayerNameChanged和OnPlayerColorChanged这两个方法
    //第一个变量(oldstr)是同步变量修改前的值，第二个(newstr)是同步变量修改后的值
    private void OnPlayerNameChanged(string oldstr, string newstr)
    {
        nameText.text = newstr;
    }
    private void OnPlayerColorChanged(Color oldCor, Color newCor)
    {
        nameText.color = newCor;
    }
    void Awake()
    {
        chat = FindObjectOfType<Chat>();
    }

    [Command]
    public void CmdSendPLayerMessage(string message)
    {

        if (chat != null)
        {
            chat.chatTextString = playerName + "说:" + message;
        }
    }


    void FixedUpdate()
    {
        if (!isLocalPlayer) return;
        isGround = Physics2D.OverlapCircle(groundCheck.position, checkRadius, ground); // 检测是否在地面上

        Move();
        Jump(); // 跳跃

    }

    void Move()
    {
        //通过键盘获取水平轴的值，范围在-1到1
        float horizontal = Input.GetAxisRaw("Horizontal");
        rb.velocity = new Vector2(horizontal * moveSpeed, rb.velocity.y); // 设置刚体速度
        if (horizontal != 0)
        {
            transform.GetChild(0).localScale = new Vector3(-horizontal, 1, 1); // 翻转角色
        }
    }

    void Jump()
    {
        // 是否在地面上
        if (isGround)
        {
            jumpCount = canJumpCount; // 如果在地面上，设置可跳跃次数为canJumpCount
            isJump = false; // 设置 isJump 为 false
        }

        if (jumpPressed)
        {
            //如果按下跳跃键// 在地面上
            if (isGround)
            {
                isJump = true; // 设置 isJump 为 true
                rb.velocity = new Vector2(rb.velocity.x, jumpForce); // 设置刚体速度
                jumpCount--; // 跳跃次数减 1
                jumpPressed = false; // 设置 jumpPressed 为 false
            }
            else if (jumpCount > 0)
            {
                Debug.Log("二段跳");
                rb.velocity = new Vector2(rb.velocity.x, jumpForce); // 设置刚体速度
                jumpCount--; // 跳跃次数减 1
                jumpPressed = false; // 设置 jumpPressed 为 false
            }
        }
    }

    // 动画
    void SwitchAnim()
    {
        if (Mathf.Abs(rb.velocity.x) > 0)
        {
            anim.SetBool("isRun", true);
            anim.SetBool("isIdle", false);
        }
        else
        {
            anim.SetBool("isRun", false);
            anim.SetBool("isIdle", false);
        }

        if (isGround)
        {
            anim.SetBool("isJump", false);
            anim.SetBool("isFall", false);
            anim.SetBool("isIdle", true);
        }
        else if (rb.velocity.y > 0)
        {
            // 播放跳跃动画
            anim.SetBool("isJump", true);
            anim.SetBool("isFall", false);
            anim.SetBool("isRun", false);
            anim.SetBool("isIdle", false);
        }
        else if (rb.velocity.y < 0)
        {
            // 播放下落动画
            anim.SetBool("isFall", true);
            anim.SetBool("isJump", false);
            anim.SetBool("isRun", false);
            anim.SetBool("isIdle", false);
        }
        //攻击动画
        if (Input.GetMouseButtonDown(0))
        {
            anim.SetTrigger("isAttack");
            anim.SetBool("isIdle", false);
        }
    }

    public override void OnStartLocalPlayer()
    {
        chat.playerControl = this;
        //摄像机与角色绑定
        Camera.main.transform.SetParent(transform);
        Camera.main.transform.localPosition = new Vector3(0, 0, Camera.main.transform.position.z);

        //随机生成颜色和名字
        ChangedColorAndName();
    }

    //player 的随机名称和颜色
    private void ChangedColorAndName()
    {
        //随机名称和颜色
        var tempName = $"Player{Random.Range(1, 999)}";
        var tempColor = new Color(Random.Range(0, 1f), Random.Range(0, 1f), Random.Range(0, 1f), 1);

        //同步变量进行修改
        CmdSetupPlayer(tempName, tempColor);
    }

    //对于同步变量的修改，使用[Command]标记(针对方法的标记，方法名以Cmd开头)
    //通过这个方法同时对name和颜色进行修改
    [Command]
    private void CmdSetupPlayer(string name, Color color)
    {
        playerName = name;
        playerColor = color;
    }
}